import React, { Component } from 'react'
import { Card, Form, Input, Cascader, Button, message } from 'antd'
import { ArrowLeftOutlined } from '@ant-design/icons'
import withRouter from '../../utils/withRouter'
import {reqCategoryList, reqAddOrUpdateProduct} from '../../api/api'
import PicturesWall from './pictures-wall.jsx'
import RichTextEditor from './rich-text-editor.jsx'

const { Item } = Form
const { TextArea } = Input



class ProductAddUpdate extends Component {

  state = {
    options: [],
    parentId: '0',
  }
  // 创建ref
  addUpdateForm = React.createRef()
  pw = React.createRef() //接收图片的ref
  editor = React.createRef()

  // 提交
  submit = async () => {
    // 表单验证，通过才发请求
    const value = await this.addUpdateForm.current.validateFields ()
    if (value) {
      // alert ('tijiao')
      // console.log (value)
      // 1 收集数据，行程product参数对象
      const {name,desc,price,category} = value
      let pCategoryId, categoryId
      if (category.length===1) {
        pCategoryId = '0'
        categoryId = category[0]
      } else {
        pCategoryId = category[0]
        categoryId = category[1]
      }
      const imgs = this.pw.current.getImgs () // 图片数组
      const detail = this.editor.current.getDetail () // 富文本编辑
      const product = {name, desc, price, imgs, detail, pCategoryId, categoryId}
      // 如果是更新, 需要添加_id
      if(this.isUpdate){
        product._id = this.product._id
      }
      // 2 调用接口
      const result = (await reqAddOrUpdateProduct(product))
      // 3 根据结果提示
      if (result.status===0) {
        message.success(`${this.isUpdate ? '更新' : '添加'}商品成功!`)
        this.props.navigate(-1)
      } else {
        message.error(`${this.isUpdate ? '更新' : '添加'}商品失败!`)
      }
    }
  }

   // 验证价格
   validatePrice = async (rule, value) => {
    if (value*1>0) {
      return Promise.resolve()//成功
    } else {
      return Promise.reject('请输入正确价格')
    }
  }

  // 商品分类级联
  loadData = async (selectedOptions) => {
    // 得到选择的option对象
    const targetOption = selectedOptions[0];
    targetOption.loading = true; // load options lazily
    // 根据当前选中项获取二级列表
    const subCategoryList = await this.getCategoryList (targetOption.value)
    targetOption.loading = false;
    if (subCategoryList && subCategoryList.length>0) {
      const childOptions = subCategoryList.map (c => ({
        value: c._id,
        label: c.name,
        isLeaf: true,
      }))
      // 关联到当前option
      targetOption.children = childOptions
    } else {
      targetOption.isLeaf = true
    }
    this.setState ({
      options: [...this.state.options]
    })
  };

  // 获取一级、二级分类列表
  getCategoryList = async (parentId) => {
    parentId = parentId || this.state.parentId
    const result = await reqCategoryList ({parentId})
    if (result.status === 0) {
      const categoryList = result.data
      // 判断一二级分类
      if (parentId === '0') {
        this.initOptions (categoryList)
      } else { 
        return categoryList // 二级列表
      }
    }
  }

  initOptions = async (categoryList) => {
    const options = categoryList.map (c => ({
      value: c._id,
      label: c.name,
      isLeaf: false,
    }))

    // 如果是二级分类商品更新  要产生对应二级列表
    const {isUpdate, product} = this
    const {pCategoryId} = product
    if (isUpdate && pCategoryId !== '0') {
      const subCategoryList = await this.getCategoryList (pCategoryId)
      // 生成对应二级分类列表的options
      const childOptions = subCategoryList.map (c => ({
        value: c._id,
        label: c.name,
        isLeaf: true,
      }))
      // 关联到对应一级option
      const targetOption = options.find (option => option.value === pCategoryId)
      targetOption.children = childOptions
    }
    this.setState ({options})
  }

  componentDidMount () {
    this.getCategoryList ()
  }

  UNSAFE_componentWillMount () {
    // 取出携带的state参数
    const product = this.props.location.state
    this.isUpdate = !!product // 标识添加修改
    this.product = product || {}
    console.log (product)
  }

  render() {
    const {isUpdate, product} = this
    const {categoryId, pCategoryId, imgs, detail} = product
    
    // 接收级联分类的数组
    const categoryIds = []
    if (isUpdate) {
      if (pCategoryId === '0') {
        categoryIds.push (categoryId) // 一级分类商品
      } else {
        categoryIds.push (pCategoryId) // 二级分类商品
        categoryIds.push (categoryId)
      }
    }

    const formItemLayout = {
      labelCol: { span: 2 },
      wrapperCol: { span: 8 }
    }
    const title = (
      <span>
        <Button
          type='link'
          onClick={() => this.props.navigate(-1)}>
          <ArrowLeftOutlined style={{ marginRight: 5, fontSize: 20 }} />
        </Button>
        <span>{isUpdate? '修改商品':'添加商品'}</span>
      </span>)

    return (
      <Card title={title}>
        <Form {...formItemLayout} ref={this.addUpdateForm} initialValues={product}>
          <Item label="商品名称" name='name'
            rules={[
              {
                required: true,
                message: '请输入商品名称!',
              },
            ]}>
            <Input placeholder="input placeholder" />
          </Item>
          <Item label="商品描述" name='desc'
            rules={[
              {
                required: true,
                message: '请输入商品描述!',
              },
            ]}>
            <TextArea placeholder="input placeholder" />
          </Item>
          <Item label="商品价格" name='price'
            rules={[
              {
                required: true,
                message: '请输入商品价格!',
              },
              {validator: this.validatePrice}
            ]}>
            <Input type='number' addonAfter="元" />
          </Item>
          <Item label="商品分类" name='category' initialValue={categoryIds}
          rules={[
            {
              required: true,
              message: '请输入商品分类!',
            },
          ]}>
          <Cascader options={this.state.options} loadData={this.loadData}  />
          </Item>
          <Item label="商品图片">
            <PicturesWall ref={this.pw} imgs={imgs}/>
          </Item>
          <Item label="商品详情" labelCol={{ span: 2 }} wrapperCol={{ span: 20 }}>
            <RichTextEditor ref= {this.editor} detail={detail}></RichTextEditor>
          </Item>
          <Item >
            <Button type='primary' onClick={this.submit}>提交</Button>
          </Item>
        </Form>
      </Card>
    )
  }
}

export default withRouter(ProductAddUpdate)
